﻿ IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'ProveedorSave')
	BEGIN
		DROP  Procedure  ProveedorSave
	END
GO

CREATE PROCEDURE ProveedorSave
	(	
		@id						AS INT,
		@nombre					AS VARCHAR(30),
		@empresaId				AS INT,		
		@cedula					AS VARCHAR(30),
		@telefono				AS VARCHAR(30),		
		@email					AS VARCHAR(100),
		@paisId					AS INT,		
		@provinciaId			AS INT,
		@direccion				AS VARCHAR(200),
		@notas					AS VARCHAR(200),
		@diasCredito			AS INT,
		@limiteCredito			AS MONEY,	
		@tipoId					AS INT,	
		@user					AS VARCHAR(30)		
	)	
AS
BEGIN	
	SET NOCOUNT ON

	DECLARE @currentDate AS DATETIME
	SET @currentDate = GETDATE()
	
	IF EXISTS(SELECT 1 FROM Proveedor WHERE ProveedorId = @id)
	BEGIN
		UPDATE Proveedor
		SET Nombre = @nombre,				
			Cedula = @cedula,
			Telefono = @telefono,
			Email = @email,
			PaisId = @paisId,
			ProvinciaId =  @provinciaId,
			Direccion =  @direccion,
			Notas =  @notas,
			DiasCredito =  @diasCredito,
			LimiteCredito =  @limiteCredito,	
			TipoId = @tipoId,		
			Activo = 1,
			FechaModificacion = @currentDate,
			ModificadoPor = @user		
		WHERE ProveedorId = @id
	
	END
	ELSE
	BEGIN	
		SELECT @id = ISNULL(MAX(ProveedorId),0)+1 FROM Proveedor

		INSERT INTO Proveedor
			(ProveedorId, Nombre, Cedula, Telefono, Email, PaisId, ProvinciaId, Direccion, 
			 Notas, DiasCredito, LimiteCredito, TipoId,
			 Activo, FechaCreacion, FechaModificacion, ModificadoPor, EmpresaId)
		VALUES
			(@id, @nombre, @cedula, @telefono, @email, @paisId, @provinciaId, @direccion,
			 @notas, @diasCredito, @limiteCredito, @tipoId,
			 1, @currentDate, @currentDate, @user, @empresaId)	
	END
	
	SET NOCOUNT OFF
END  